/* eslint-disable react/jsx-key */
import React, { useState, useRef } from 'react';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { Modal, Button, Popconfirm, Select, Tag } from 'antd';
import { useRequest } from 'ahooks';
import { doFetch, getFetch } from '@/utils/doFetch';
import { UserAddOutlined } from '@ant-design/icons';
import { role, area } from '@/services/api';

const { Option, OptGroup } = Select;

let defaultFields = {
  name: {
    value: null,
    type: 'input',
    title: '角色名',
    name: ['name'],
    required: true,
  },
  role_type: {
    value: null,
    type: 'select',
    title: '角色类型',
    name: ['role_type'],
    required: true,
    options: [
      {
        label: '系统管理',
        value: 0,
      },
      {
        label: '微信公众号',
        value: 1,
      },
    ],
  },
  area_ids: {
    value: null,
    type: 'select',
    title: '区域',
    name: ['area_ids'],
    required: true,
    multiple: true,
    options: {
      database: area,
      params: {
        is_all: 1,
      },
    },
    col: {
      span: 24,
    },
  },
};

let Role = ({ route }) => {
  let columns = [
    {
      title: '角色名',
      dataIndex: 'name',
      key: 'name',
      width: 88,
    },
    {
      title: '角色类型',
      dataIndex: 'role_type',
      key: 'role_type',
      width: 120,
      render: (row, record) => <a>{record.role_type == '0' ? '系统管理' : '微信公众号'}</a>,
    },
    {
      title: '区域',
      dataIndex: 'areas',
      key: 'areas',
      width: 120,
      render: (row, record) => {
        return record.areas
          ? record.areas.map((it) => (
            <span
              key={it.id}
              style={{
                padding: '2px 4px',
                margin: '0 1px 1px 1px',
                backgroundColor: 'rgba(255,255,255,0.2)',
              }}
            >
              {it.area_name}
            </span>
          ))
          : '-';
      },
    },
    {
      title: '权限',
      dataIndex: 'menus',
      key: 'menus',
      render: (row, record) => {
        let menus = record.menus ?? [];
        let pc = record?.menus
          ? record?.menus.filter((it) => it.menu_type == 'pc').map((it) => it.name)
          : [],
          wx = record?.menus
            ? record?.menus.filter((it) => it.menu_type == 'wechat').map((it) => it.name)
            : [];
        return (
          <div className="rows">
            {record.role_type == 0 ? (
              <div className="rows">
                <span>系统：</span>
                {pc.map((it) => (
                  <span
                    style={{
                      padding: '2px 4px',
                      margin: '0 1px 1px 1px',
                      backgroundColor: 'rgba(255,255,255,0.2)',
                    }}
                  >
                    {it}
                  </span>
                ))}
              </div>
            ) : (
              <div className="rows">
                <span>微信：</span>
                {wx.map((it) => (
                  <span
                    style={{
                      padding: '2px 4px',
                      margin: '0 1px 1px 1px',
                      backgroundColor: 'rgba(255,255,255,0.2)',
                    }}
                  >
                    {it}
                  </span>
                ))}
              </div>
            )}
          </div>
        );
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 170,
      render: (text, record, _, action) => [
        // eslint-disable-next-line react/jsx-key
        <a
          style={{ color: '#1890ff' }}
          onClick={() => {
            let sub = data?.data.filter(it => !it.menu_key.includes("system")),
              end = data?.data.filter(it => it.menu_key.includes("system")),
              respc = [...sub, ...end];

            let pcarr =
              respc &&
              respc
                .filter((it) => it.menu_type == 'pc')
                .map((it) => ({
                  label: it.name,
                  value: it.id,
                })),
              pcids = record?.menus
                ? record?.menus.filter((it) => it.menu_type == 'pc').map((it) => it.menu_id)
                : [],
              wxarr =
                data?.data &&
                data?.data
                  .filter((it) => it.menu_type == 'wechat')
                  .map((it) => ({
                    label: it.name,
                    value: it.id,
                  })),
              wxids = record?.menus
                ? record?.menus.filter((it) => it.menu_type == 'wechat').map((it) => it.menu_id)
                : [];

            cv(true);
            cf((fields) => {
              return {
                pc_menu_ids: {
                  value: pcids,
                  type: 'select',
                  title: '系统权限列表',
                  name: ['pc_menu_ids'],
                  required: false,
                  multiple: true,
                  options: pcarr,
                  col: {
                    span: 24,
                  },
                  hides: record.role_type == 1,
                },
                wx_menu_ids: {
                  value: wxids,
                  type: 'select',
                  title: '微信权限列表',
                  name: ['wx_menu_ids'],
                  required: false,
                  multiple: true,
                  options: wxarr,
                  col: {
                    span: 24,
                  },
                  hides: record.role_type == 0,
                },
              };
            });
            ciftype({
              val: 'roledone',
              title: '配置权限',
              id: record.id,
            });
          }}
        >
          配置权限
        </a>,
        <a
          style={{ color: '#1890ff' }}
          onClick={() => {
            cv(true);
            cf(() => {
              for (let i in defaultFields) {
                defaultFields[i].value = record[i];
                if (i == 'area_ids') {
                  defaultFields[i].value = record.areas.map((it) => it.area_id);
                }
              }
              return { ...defaultFields };
            });
            ciftype({
              val: 'edit',
              title: '编辑角色',
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <Popconfirm
          placement="bottom"
          title={'确认删除该角色？'}
          onConfirm={() => {
            run({ url: '/vehicle-api/role/' + record.id, params: {}, type: 'delete' });
          }}
          okText="删除"
          cancelText="取消"
        >
          <a style={{ color: '#f50' }}>删除</a>
        </Popconfirm>,
      ],
    },
  ],
    [visible, cv] = useState(false),
    [iftype, ciftype] = useState({}),
    [fields, cf] = useState(defaultFields);

  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }

  let { run, loading } = useRequest(doFetch, {
    debounceWait: 300, //防抖
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result, params) => {
      if (result.code == 0) {
        reload();
        cv(false);
      }
    },
  }),
    { data } = useRequest(() => {
      return getFetch({ url: '/vehicle-api/menu', params: {} });
    });

  // columns.map((it) => {
  //   obj[it.key] = it.title;

  // })
  // console.log(JSON.stringify(obj))

  return (
    <div style={{ width: '100%', height: '100%' }}>
      <Modal
        visible={visible}
        title={iftype.title}
        onCancel={() => {
          cv(false);
        }}
        footer={false}
        destroyOnClose={true}
      >
        <InitForm
          fields={fields}
          submitData={(values) => {
            if (iftype.val == 'add') {
              run({ url: '/vehicle-api/role', params: values });
            } else if (iftype.val == 'edit') {
              run({ url: '/vehicle-api/role/' + iftype.id, params: values, type: 'PUT' });
            } else {
              let { pc_menu_ids, wx_menu_ids } = values ?? {};
              pc_menu_ids = pc_menu_ids ?? [];
              wx_menu_ids = wx_menu_ids ?? [];
              let newparams = {
                menu_ids: [...pc_menu_ids, ...wx_menu_ids],
                id: iftype.id,
              };
              run({ url: '/vehicle-api/role/role_menu', params: { ...newparams }, type: 'PUT' });
            }
          }}
          onChange={(changedValues, allValues) => {
            //联动操作
          }}
          submitting={loading}
        />
      </Modal>
      <AutoTable
        pagetitle={route.name}
        pageextra={[
          <Button
            type="primary"
            icon={<UserAddOutlined />}
            onClick={() => {
              cf(() => {
                for (let i in defaultFields) {
                  defaultFields[i].value = i == 'area_ids' ? [] : null;
                }
                return { ...defaultFields };
              });
              cv(true);
              ciftype({
                title: '新增角色',
                val: 'add',
              });
            }}
          />,
        ]}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/vehicle-api/role"
        rowClassName={(record, index) => {
          let className = index % 2 ? 'shallow_gray' : 'deep_gray';
          return className;
        }}
        columns={columns}
      />
    </div>
  );
};

export default Role;
